package com.apkdv.playandroid

import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.apkdv.mvvmfast.base.BaseViewModel
import com.apkdv.mvvmfast.entity.*
import com.apkdv.mvvmfast.ext.launchWithFlow
import com.apkdv.mvvmfast.ext.netCatch
import com.apkdv.mvvmfast.ext.next
import com.apkdv.mvvmfast.ext.showToast
import com.apkdv.playandroid.api.API
import com.apkdv.playandroid.entity.PublicHistoryData
import kotlinx.coroutines.flow.onStart

/**
 * 广场
 */
class SquareViewModel : BaseViewModel() {

    //广场
    val squareIndexState: LazyListState = LazyListState()

    //每日一问
    val questionIndexState: LazyListState = LazyListState()

    //体系
    val systemIndexState: LazyListState = LazyListState()

    //导航
    val naviIndexState: LazyListState = LazyListState()

    //导航数据

    var navData by mutableStateOf<LoadState>(LoadNano)

    //获取导航数据
    fun getNavi() = request {
        launchWithFlow({
            API.getPublicNumberList()
        }, {
            it.message.showToast()
        }).onStart {
            navData = LoadLoading
        }.netCatch {
            navData = LoadError(this)
        }.next {
            navData = LoadSuccess(this)
        }
    }

    var userData by mutableStateOf<LoadState>(LoadNano)
    var userDataIndex = HashMap<Int, Int>()
    val userDataList by mutableStateOf<HashMap<Int, PublicHistoryData?>>(hashMapOf())
    fun getDataById(id: Int) = request {
        if (!userDataIndex.containsKey(id)) {
            userDataIndex[id] = 1
        }
        val page = userDataIndex[id] ?: 1
        launchWithFlow({
            API.getPublicHistoryData(id, page)
        }, {
            it.message.showToast()
        }).onStart {
            userData = LoadLoading
        }.netCatch {
            userData = LoadError(this)
        }.next {
            userDataIndex[id] = page + 1
            userDataList[id] = this
            userData = LoadSuccess(this)
        }
    }
}